<template>
    <div>
      <el-tree
        :data="dataJson"
        show-checkbox
        node-key="id"
        :expand-on-click-node="false">
      <span slot-scope="{ node, data }">
        <span class="tree-span">{{ node.label }}</span>
        <span class="tree-span">{{ data.url }}</span>
        <!--<span>{{data.seq}}</span>-->
        <span class="tree-span">
          <el-button
            type="text"
            size="mini"
            style="margin-right: 10px"
            @click="() => append(data)">
            <i class="fa fa-plus-square-o fa-fw">&nbsp;添加</i>
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)">
              <i class="fa fa-trash-o fa-fw">&nbsp;删除</i>
          </el-button>
        </span>
      </span>
      </el-tree>
    </div>
</template>

<script>
import {fetch} from '@/utils/http'
let id = 1000
export default {
  name: 'index',
  data () {
    return {
      treeData: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1',
          children: [{
            id: 9,
            label: '三级 1-1-1'
          }, {
            id: 10,
            label: '三级 1-1-2'
          }]
        }]
      }, {
        id: 2,
        label: '一级 2',
        children: [{
          id: 5,
          label: '二级 2-1'
        }, {
          id: 6,
          label: '二级 2-2'
        }]
      }, {
        id: 3,
        label: '一级 3',
        children: [{
          id: 7,
          label: '二级 3-1'
        }, {
          id: 8,
          label: '二级 3-2'
        }]
      }]
    }
  },
  computed: {
    dataJson () {
      return JSON.parse(JSON.stringify(this.treeData))
    }
  },
  mounted: function () {
    this.fetch()
  },
  methods: {
    append (data) {
      const newChild = { id: id++, label: 'testtest', children: [] }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    },
    remove (node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },
    fetch () {
      fetch('long-base-upms/sysMenu/getAllTreeNode').then((res) => {
        if (res.status === 200) {
          this.treeData = res.data.treeNodeList
        } else {
          this.$message(res.message)
        }
      })
    }
  }
}
</script>

<style scoped>
.tree-span {
  margin-right: 10px;
}
</style>
